# @FileName  : conf.py
# @Time      : 2022/3/5 17:18
# @Author    : LuZhaoHui
# @Software  : PyCharm

from configparser import ConfigParser


class MyParser(ConfigParser):
    "Inherit from built-in class: ConfigParser"

    def optionxform(self, optionstr):
        "Rewrite without lower()"
        return optionstr


class imageCheckScpConf():
    def __init__(self, file):
        self.initVar()
        self.config = MyParser()
        self.name = file
        self.readConf()

    def initVar(self):
        # 设计配置
        self.vars = {'Conf', 'Check', 'Scp', 'Log', 'Msql'}
        self.varConf = {
            'Title': '',
            'CurOp': 0,
            'CurPath': '',
            'MainPath': '',
            'CachePath': '',
            'WindowMax': 0
        }
        self.varCheck = {
            'CheckTimer': 2000,
            'CheckIsImage': 1,
            'CheckMean': 20.0,
            'CheckImageExt': 'jpg',
            'CheckImageDpi': 300,
            'CheckImageSize': 0,
            'CheckImageMaxWidth': 0,
            'CheckImageMaxHeight': 0,
            'CheckImageNoWidth': 6
        }
        self.varScp = {
            'IsScp': 1,
            'ScpHost': '127.0.0.1',
            'ScpPort': 22,
            'ScpUser': 'root',
            'ScpPass': 'Dashen2024',
            'ScpPath': '/home/dashen/image'
        }
        self.varLog = {
            'IsLog': 1,
            'LogPath': ''
        }
        self.varMsql = {
            'IsDb': 0,
            'DbHost': '127.0.0.1',
            'DbPort': 3306,
            'DbUser': 'root',
            'DbPass': 'root',
            'DbName': 'data'
        }

    def getConfig(self, section, key):
        return self.config.get(section, key)

    def readConf(self):
        self.config.read(self.name, 'utf-8')
        # str = self.getConfig('CONF', 'Title')
        # print(str)
        vAll = vars(self)
        for var in self.vars:
            vv = vAll['var' + var]
            for k, v in enumerate(vv):
                try:
                    str = self.getConfig(var.upper(), v)
                    if isinstance(vv[v], int):
                        vv[v] = int(str)
                    elif isinstance(vv[v], float):
                        vv[v] = float(str)
                    else:
                        vv[v] = str
                except:
                    self.writeVarConf(var.upper(), v, vv[v])

    def writeConf(self):
        with open(self.name, 'w', encoding='utf-8') as f:
            self.config.write(f)

    def writeVarConf(self, var, key, value):
        self.config.set(var, key, str(value))
        self.writeConf()
